<template>
  <div class="formBox formBox2 mt-15">
    <el-form
      :model="formData"
      :rules="formRules"
      inline
      ref="ruleForm"
      label-width="150px"
      class="demo-ruleForm"
    >
      <div class="form-tit">基础信息</div>
      <el-form-item label="企业名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入企业名称"
          :disabled="isDisabled"
          maxlength="100"
        ></el-input>
      </el-form-item>
      <el-form-item label="法定代表人" prop="principal">
        <el-input
          v-model="formData.principal"
          placeholder="请输入法定代表人"
          :disabled="isDisabled"
          maxlength="100"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="areaName">
        <el-cascader
          v-model="formData.areaName"
          :options="addressOptions"
          @change="handleChange"
          placeholder="请选择地址"
          :disabled="isDisabled"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input
          type="textarea"
          v-model="formData.address"
          placeholder="请输入详细地址"
          :disabled="isDisabled"
          maxlength="100"
        ></el-input>
      </el-form-item>
      <el-form-item label="经营主体" prop="businessEntity">
        <el-select v-model="formData.businessEntity" placeholder="请选择" :disabled="isDisabled">
          <el-option
            v-for="item in businessEntityOptions"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品猪年出栏量" prop="yearSlaughterNum">
        <el-input
          v-model="formData.yearSlaughterNum"
          placeholder="请输入商品猪年出栏量"
          :disabled="isDisabled"
          maxlength="8"
        >
          <template slot="append">头</template>
        </el-input>
      </el-form-item>
      <el-form-item label="种猪年出栏量" prop="yearPigletSlaughterNum">
        <el-input
          v-model="formData.yearPigletSlaughterNum"
          placeholder="请输入种猪年出栏量"
          :disabled="isDisabled"
          maxlength="8"
        >
          <template slot="append">头</template>
        </el-input>
      </el-form-item>
      <el-form-item label="成立时间" prop="establishedTime">
        <el-date-picker
          v-model="formData.establishedTime"
          type="date"
          placeholder="选择成立时间"
          :disabled="isDisabled"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="员工人数" prop="employeesNum">
        <el-input
          v-model="formData.employeesNum"
          placeholder="请输入员工人数"
          :disabled="isDisabled"
          maxlength="18"
        >
          <template slot="append">人</template>
        </el-input>
      </el-form-item>
      <!-- <el-form-item label="智能养殖企业" prop="enterpriseType">
        <el-radio-group v-model="formData.enterpriseType">
          <el-radio :label="1" :disabled="isDisabled">是</el-radio>
          <el-radio :label="0" :disabled="isDisabled">否</el-radio>
        </el-radio-group>
      </el-form-item>-->
      <el-form-item label="展示经度" prop="longitude">
        <el-input
          v-model="formData.longitude"
          placeholder="请输入展示经度"
          :disabled="isDisabled"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item label="展示纬度" prop="latitude">
        <el-input
          v-model="formData.latitude"
          placeholder="请输入展示纬度"
          :disabled="isDisabled"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="数字猪场描述" prop="remark">
        <el-input type="textarea" v-model="formData.remark" placeholder="请输入数字猪场描述" maxlength="30" show-word-limit :disabled="isDisabled"></el-input>
      </el-form-item>-->
      <div class="form-tit">营业执照信息</div>
      <el-form-item label="统一社会信用代码" prop="creditCode">
        <el-input
          v-model="formData.creditCode"
          placeholder="请输入统一社会信用代码"
          :disabled="isDisabled"
          maxlength="18"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="注册号" prop="registrationCode">
        <el-input v-model="formData.registrationCode" placeholder="请输入注册号" :disabled="isDisabled" maxlength="50"></el-input>
      </el-form-item>-->
      <el-form-item label="类型" prop="enterpriseCategory">
        <el-input
          v-model="formData.enterpriseCategory"
          placeholder="请输入类型"
          :disabled="isDisabled"
          maxlength="50"
        ></el-input>
      </el-form-item>
      <el-form-item label="注册资本" prop="registeredCapital">
        <el-input
          v-model="formData.registeredCapital"
          placeholder="请输入注册资本"
          :disabled="isDisabled"
          maxlength="20"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="核准日期" prop="approvedDate">
        <el-date-picker
          v-model="formData.approvedDate"
          type="date"
          placeholder="选择核准日期"
          :disabled="isDisabled"
          style="width:300px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="营业期限" prop="operatingPeriod">
        <!-- <el-date-picker
          v-model="formData.operatingPeriod"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabled="isDisabled"
          style="width:300px">
        </el-date-picker>-->
        <el-date-picker
          v-model="operatingPeriodStart"
          type="date"
          placeholder="开始日期"
          :disabled="isDisabled"
          style="width:140px"
          :picker-options="{
            disabledDate (time) {
              return operatingPeriodEnd ? time.getTime() > operatingPeriodEnd : '';
            }
          }"
        ></el-date-picker>
        <span style="padding: 0 6px">-</span>
        <el-date-picker
          v-model="operatingPeriodEnd"
          type="date"
          placeholder="结束日期"
          :disabled="isDisabled"
          style="width:140px"
          :picker-options="{
            disabledDate (time) {
              return operatingPeriodStart ? time.getTime() < operatingPeriodStart : '';
            }
          }"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="登记机关" prop="registrationAuthority">
        <el-input
          v-model="formData.registrationAuthority"
          placeholder="请输入登记机关"
          :disabled="isDisabled"
          maxlength="50"
        ></el-input>
      </el-form-item>
      <el-form-item label="登记状态" prop="registrationStatus">
        <el-input
          v-model="formData.registrationStatus"
          placeholder="请输入登记状态"
          :disabled="isDisabled"
          maxlength="50"
        ></el-input>
      </el-form-item>
      <el-form-item label="经营范围" prop="businessScope">
        <el-input
          type="textarea"
          v-model="formData.businessScope"
          placeholder="请输入经营范围"
          maxlength="300"
          show-word-limit
          :disabled="isDisabled"
        ></el-input>
      </el-form-item>
      <div class="form-tit">
        证照信息
        <span class="remind">（点击上传图片，推荐大小为200*200；上传图片不超过3M，格式为jpg、png）</span>
      </div>
      <!--  -->
      <template>
        <el-form-item
          :label="item.label"
          :prop="item.value"
          class="upload-pic"
          v-for="(item,index) in imgList"
          :key="index"
        >
          <el-input v-model="formData[item.value]" style="display: none;"></el-input>
          <div v-if="isDisabled&&formData[item.value]" class="preview-img">
            <el-image
              :src="formData[item.value]"
              class="avatar"
              :preview-src-list="[formData[item.value]]"
            />
          </div>
          <el-upload
            v-else
            :disabled="isDisabled"
            class="avatar-uploader"
            :headers="headers"
            :action="action"
            :show-file-list="false"
            :on-success="handleImgSuccess"
            :before-upload="beforeImgUpload"
          >
            <img
              v-if="formData[item.value]&&formData[item.value] !==' '"
              :src="formData[item.value]"
              class="avatar"
              @click="setImgName(item.value)"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="setImgName(item.value)"></i>
            <i
              v-if="formData[item.value]&&!isDisabled&&formData[item.value] !==' '"
              class="el-icon-remove"
              @click.stop="remove(item.value)"
            ></i>
          </el-upload>
        </el-form-item>
      </template>
      <!--  -->
    </el-form>
    <div style="text-align: center;padding:20px 0">
      <el-button @click="goBack">返回</el-button>
      <el-button v-if="type!=='view'" type="primary" @click="handelsubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { closeSelectedTag } from '@/utils/index'
import { REG, TEXT_MESSAGE } from '@/utils/verification'
export default {
  name: 'dataForm',
  props: {
    isAdd: {
      type: Boolean
    }
  },
  data () {
    return {
      imgList: [
        { label: '企业图片', value: 'pictureUrl' },
        { label: '营业执照', value: 'businessLicenseUrl' },
        { label: '经营许可证', value: 'businessPermitUrl' },
        { label: '动物防疫条件合格证', value: 'certificateUrl' },
      ],
      imgName: '',
      type: this.$route.query.type,
      enterpriseId: this.$route.query.id,
      isDisabled: this.$route.query.type === 'view' ? true : false,
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now();
        },
      },
      isLoading: false,
      dataId: '',
      addressOptions: [
        {
          value: '肇庆市',
          label: '肇庆市',
          children: [
            { value: '端州区', label: '端州区',children:[
              {value:'城东',label:'城东'  },
              {value:'城西',label:'城西'},
              {value:'城南',label:'城南'},
              {value:'城北',label:'城北'},
              {value:'康乐',label:'康乐'},
              {value:'古塔',label:'古塔'  }
            ] },
            { value: '鼎湖区', label: '鼎湖区',children:[
              {value:'坑口街道',label:'坑口街道'},
              {value:'桂城街道',label:'桂城街道'},
              {value:'广利街道',label:'广利街道'},
              {value:'永安镇',label:'永安镇'},
              {value:'沙浦镇',label:'沙浦镇'},
              {value:'凤凰镇',label:'凤凰镇'},
              {value:'莲花镇',label:'莲花镇'}
            ] },
            { value: '广宁县', label: '广宁县',children:[
              {value:'南街镇',label:'南街镇'},
              {value:'赤坑镇',label:'赤坑镇'},
              {value:'北市镇',label:'北市镇'},
              {value:'江屯镇',label:'江屯镇'},
              {value:'联和镇',label:'联和镇'},
              {value:'潭布镇',label:'潭布镇'},
              {value:'排沙镇',label:'排沙镇'},
              {value:'石涧镇',label:'石涧镇'},
              {value:'宾亨镇',label:'宾亨镇'},
              {value:'横山镇',label:'横山镇'},
              {value:'五和镇',label:'五和镇'},
              {value:'木格镇',label:'木格镇'},
              {value:'洲仔镇',label:'洲仔镇'},
              {value:'古水镇',label:'古水镇'},
              {value:'坑口镇',label:'坑口镇'},
              {value:'葵洞镇',label:'葵洞镇'},
              {value:'螺岗镇',label:'螺岗镇'},
              {value:'清桂镇',label:'清桂镇'},
              {value:'石咀镇',label:'石咀镇'},
              {value:'深坑乡',label:'深坑乡'}
            ] },
            { value: '怀集县', label: '怀集县',children:[
              {value:'梁村镇',label:'梁村镇'},
              {value:'大岗镇',label:'大岗镇'},
              {value:'岗坪镇',label:'岗坪镇'},
              {value:'冷坑镇',label:'冷坑镇'},
              {value:'马宁镇',label:'马宁镇'},
              {value:'蓝钟镇',label:'蓝钟镇'},
              {value:'怀城镇',label:'怀城镇'},
              {value:'闸岗镇',label:'闸岗镇'},
              {value:'坳仔镇',label:'坳仔镇'},
              {value:'汶朗镇',label:'汶朗镇'},
              {value:'甘洒镇',label:'甘洒镇'},
              {value:'凤岗镇',label:'凤岗镇'},
              {value:'洽水镇',label:'洽水镇'},
              {value:'中洲镇',label:'中洲镇'},
              {value:'连麦镇',label:'连麦镇'},
              {value:'永固镇',label:'永固镇'},
              {value:'诗洞镇',label:'诗洞镇'},
              {value:'桥头镇',label:'桥头镇'},
              {value:'下帅乡',label:'下帅乡'}
            ]},
            { value: '封开县', label: '封开县',children:[
              {value:'长岗镇',label:'长岗镇'},
              {value:'江口镇',label:'江口镇'},
              {value:'南丰镇',label:'南丰镇'},
              {value:'平凤镇',label:'平凤镇'},
              {value:'大洲镇',label:'大洲镇'},
              {value:'都平镇',label:'都平镇'},
              {value:'江川镇',label:'江川镇'},
              {value:'大玉口镇',label:'大玉口镇'},
              {value:'河儿口镇',label:'河儿口镇'},
              {value:'长安镇',label:'长安镇'},
              {value:'金装镇',label:'金装镇'},
              {value:'白垢镇',label:'白垢镇'},
              {value:'莲都镇',label:'莲都镇'},
              {value:'渔涝镇',label:'渔涝镇'},
              {value:'杏花镇',label:'杏花镇'},
              {value:'罗董镇',label:'罗董镇'}
            ]},
            { value: '德庆县', label: '德庆县',children:[
              {value:'新圩镇',label:'新圩镇'},
              {value:'官圩镇',label:'官圩镇'},
              {value:'马圩镇',label:'马圩镇'},
              {value:'高良镇',label:'高良镇'},
              {value:'莫村镇',label:'莫村镇'},
              {value:'永丰镇',label:'永丰镇'},
              {value:'武垄镇',label:'武垄镇'},
              {value:'播植镇',label:'播植镇'},
              {value:'凤村镇',label:'凤村镇'},
              {value:'九市镇',label:'九市镇'},
              {value:'悦城镇',label:'悦城镇'}
            ] },
            { value: '高要市', label: '高要市',children:[
              {value:'南岸街道',label:'南岸街道'},
              {value:'河台镇',label:'河台镇'},
              {value:'乐城镇',label:'乐城镇'},
              {value:'水南镇',label:'水南镇'},
              {value:'禄步镇',label:'禄步镇'},
              {value:'小湘镇',label:'小湘镇'},
              {value:'大湾镇',label:'大湾镇'},
              {value:'新桥镇',label:'新桥镇'},
              {value:'白诸镇',label:'白诸镇'},
              {value:'长安镇',label:'长安镇'},
              {value:'莲塘镇',label:'莲塘镇'},
              {value:'活道镇',label:'活道镇'},
              {value:'蛟塘镇',label:'蛟塘镇'},
              {value:'回龙镇',label:'回龙镇'},
              {value:'白土镇',label:'白土镇'},
              {value:'金渡镇',label:'金渡镇'},
              {value:'金利镇',label:'金利镇'},
              {value:'蚬岗镇',label:'蚬岗镇'}
            ] },
            { value: '四会市', label: '四会市',children:[
              {value:'东城街道',label:'东城街道'},
              {value:'城中街道',label:'城中街道'},
              {value:'贞山街道',label:'贞山街道'},
              {value:'龙甫镇',label:'龙甫镇'},
              {value:'地豆镇',label:'地豆镇'},
              {value:'威整镇',label:'威整镇'},
              {value:'罗源镇',label:'罗源镇'},
              {value:'迳口镇',label:'迳口镇'},
              {value:'大沙镇',label:'大沙镇'},
              {value:'石狗镇',label:'石狗镇'},
              {value:'下茆镇',label:'下茆镇'},
              {value:'江谷镇',label:'江谷镇'},
              {value:'黄田镇',label:'黄田镇'}
            ] }
          ]
        }
      ],
      // addressOptions: [
      //   {
      //     value: '抚州市',
      //     label: '抚州市',
      //     children: [
      //       {
      //         value: '临川区',
      //         label: '临川区'
      //       },
      //       {
      //         value: '东乡区',
      //         label: '东乡区'
      //       },
      //       {
      //         value: '南城县',
      //         label: '南城县'
      //       },
      //       {
      //         value: '黎川县',
      //         label: '黎川县'
      //       },
      //       {
      //         value: '南丰县',
      //         label: '南丰县'
      //       },
      //       {
      //         value: '崇仁县',
      //         label: '崇仁县'
      //       },
      //       {
      //         value: '乐安县',
      //         label: '乐安县'
      //       },
      //       {
      //         value: '宜黄县',
      //         label: '宜黄县'
      //       },
      //       {
      //         value: '金溪县',
      //         label: '金溪县'
      //       },
      //       {
      //         value: '资溪县',
      //         label: '资溪县'
      //       },
      //       {
      //         value: '广昌县',
      //         label: '广昌县'
      //       }
      //     ]
      //   }
      // ],
      businessEntityOptions: [
        { value: 1, label: '肉鸭场' },
        { value: 2, label: '养猪场' },
        { value: 3, label: '饲料经销商' },
        { value: 4, label: '蛋鸡场' }
      ],
      formData: {
        enterpriseType: 0,
        pictureUrl: '',
        businessLicenseUrl: '',
        businessPermitUrl: '',
        certificateUrl: '',
        businessEntity: ''
      },
      formRules: {
        name: [
          { required: true, message: '请输入企业名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在20个字符以内', trigger: 'blur' }
        ],
        principal: [
          { required: true, message: '请输入法定代表人', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在10个字符以内', trigger: 'blur' }
        ],
        areaName: [
          { required: true, message: '请输入地址', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在20个字符以内', trigger: 'blur' }
        ],
        businessEntity: [
          { required: true, message: '请选择经营主体', trigger: 'change' }
        ],
        yearSlaughterNum: [
          { pattern: REG.integer, message: TEXT_MESSAGE.integer, trigger: 'blur' }
        ],
        yearPigletSlaughterNum: [
          { pattern: REG.integer, message: TEXT_MESSAGE.integer, trigger: 'blur' }
        ],
        employeesNum: [
          { pattern: REG.integer, message: TEXT_MESSAGE.integer, trigger: 'blur' }
        ],
        longitude: [
          { pattern: REG.decimalpoint, message: TEXT_MESSAGE.decimalpoint, trigger: 'blur' }
        ],
        latitude: [
          { pattern: REG.decimalpoint, message: TEXT_MESSAGE.decimalpoint, trigger: 'blur' }
        ],
        creditCode: [
          { pattern: REG.creditCode, message: TEXT_MESSAGE.creditCode, trigger: 'blur' }
        ],
        registeredCapital: [
          { pattern: REG.decimals, message: TEXT_MESSAGE.decimals, trigger: 'blur' }
        ],
      },
      areaNameValue: '',
      bindStatus: 'BIND',
      action: process.env.VUE_APP_BASE_API + 'enterprise/uploadPhoto',
      headers: {
        Authorization: localStorage.token
      },
      operatingPeriodStart: '',
      operatingPeriodEnd: ''
    };
  },
  mounted () {
    if (this.type !== 'add') {
      this.getEnterpriseInfo();
    }
  },
  methods: {
    getEnterpriseInfo () {
      this.$api.data.getEnterpriseInfo({
        enterpriseId: this.enterpriseId
      }).then(res => {
        this.formData = res.data || {};
        this.formData.areaName = this.formData.areaName.split('/');
        this.formData.establishedTime = this.formData.establishedTime ? new Date(this.formData.establishedTime) : '';
        let operatingPeriod = this.formData.operatingPeriod || '';
        operatingPeriod = operatingPeriod ? operatingPeriod.split('至') : []
        // this.formData.operatingPeriod = operatingPeriod;
        this.operatingPeriodStart = operatingPeriod[0]
        this.operatingPeriodEnd = operatingPeriod[1] === '无固定期限' ? '' : operatingPeriod[1]
      }).catch(() => {
      })
    },
    handelsubmit () {
      this.formData.establishedTime = this.formData.establishedTime ? this.Moment(this.formData.establishedTime).format('YYYY-MM-DD') : '';
      // const operatingPeriod = this.formData.operatingPeriod || [];
      // this.formData.operatingPeriod = operatingPeriod.length ? `${this.Moment(operatingPeriod[0]).format('YYYY-MM-DD')}至${this.Moment(operatingPeriod[1]).format('YYYY-MM-DD')}`: '';
      if (this.operatingPeriodStart && this.operatingPeriodEnd) {
        this.formData.operatingPeriod = `${this.Moment(this.operatingPeriodStart).format('YYYY-MM-DD')}至${this.Moment(this.operatingPeriodEnd).format('YYYY-MM-DD')}`;
      } else if (this.operatingPeriodStart && !this.operatingPeriodEnd) {
        this.formData.operatingPeriod = `${this.Moment(this.operatingPeriodStart).format('YYYY-MM-DD')}至无固定期限`;
      } else if (!this.operatingPeriodStart && this.operatingPeriodEnd) {
        this.$message.error('请选择营业期限开始时间');
        return;
      }
      this.formData.approvedDate = this.formData.approvedDate ? this.Moment(this.formData.approvedDate).format('YYYY-MM-DD') : '';
      if (this.formData.areaName) this.areaNameValue = this.formData.areaName.join('/');
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let param = JSON.parse(JSON.stringify(this.formData));
          param.pictureUrl = param.pictureUrl || ' '
          param.businessScope = param.businessScope || ' '
          param.businessPermitUrl = param.businessPermitUrl || ' '
          param.certificateUrl = param.certificateUrl || ' '
          // console.log(param)
          // return false
          param.projectId = this.$store.state.user.projectId;
          param.areaName = this.areaNameValue;
          param.enterpriseType = this.formData.enterpriseType || 0;
          param.source = 0
          if (!this.isAdd) {
            param.enterpriseId = Number(this.enterpriseId);
          }
          this.$api.data.saveEnterpriseInfo(param).then(() => {
            let message = ''
            if (!this.isAdd) {
              message = '编辑养殖企业成功'
            } else {
              message = '新增养殖企业成功'
            }
            this.$message({
              message: message,
              type: 'success'
            })
            this.goBack()
          }).catch(() => {
          })
        }
      })
    },
    goBack () {
      this.$bus.$emit('refreshDataList')
      closeSelectedTag(this.$route, '/dataManage/index')
    },
    handleChange (value) {
      if (value) this.areaNameValue = value.join('/');
    },
    setImgName (name) {
      this.imgName = name
    },
    handleImgSuccess (res, file) {
      // this.formData.pictureUrl = res.data
      this.formData[this.imgName] = res.data
    },
    remove (name) {
      // this.formData.pictureUrl = '';
      this.formData[name] = ' '
    },
    beforeImgUpload (file) {
      const isJPG = ['image/jpg', 'image/jpeg', 'image/png'].indexOf(file.type);
      const isLt2M = file.size / 1024 / 1024 < 3;

      if (isJPG < 0) {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 3MB!');
        return false;
      }
      return isJPG && isLt2M;
    }
  }
}
</script>

<style lang="scss" scoped>
.el-textarea {
  line-height: 20px;
}
</style>